package cn.org.rookie.jeesdp.system.service;

import cn.org.rookie.jeesdp.core.utils.SecurityUtils;
import cn.org.rookie.jeesdp.mapper.sql.Wrapper;
import cn.org.rookie.jeesdp.service.impl.BaseServiceImpl;
import cn.org.rookie.jeesdp.system.entity.Menu;
import cn.org.rookie.jeesdp.system.mapper.MenuMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class MenuService extends BaseServiceImpl<Menu, String, MenuMapper> {

    public List<Menu> selectAll() {
        String type = Objects.requireNonNull(SecurityUtils.getUser()).getType();
        if ("super".equals(type)) {
            return mapper.selectMenuByPid("0");
        } else {
            return mapper.selectMenuByUserIdAndPid(SecurityUtils.getUser().getId(), "0");
        }
    }

    public List<Menu> selectByPid(String pid) {
        return mapper.findBy(Wrapper.init().equal("pid", pid));
    }

    public List<Menu> loadChildren(List<Menu> menus) {
        menus.forEach(item -> {
            List<Menu> children = selectByPid(item.getId());
            if (!children.isEmpty()) {
                item.setChildren(children);
                loadChildren(children);
            }
        });
        return menus;
    }
}
